#include <iostream>
#include <string>
#include <cstring>
#include <WinSock2.h>

#pragma warning(disable:4996)
#pragma comment(lib, "ws2_32.lib")

using namespace std;

string serverip = "47.115.217.7";
uint16_t serverport = 8080;

int main()
{
    // 初始化 WinSocket
    WSADATA wsd;
    if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) 
    {   
        /*进行WinSocket的初始化,
        windows 初始化socket网络库，申请2，2的版本，windows socket编程必须先初始化。*/
        cout << "WSAStartup Error = " << WSAGetLastError() << endl;
        return 0;
    }
    else 
    {
        cout << "WSAStartup Success" << endl;
    }

    // 创建套接字
    // SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock == SOCKET_ERROR)
    {
        cout << "socket Error = " << WSAGetLastError() << endl;
        return 1;
    }
    else 
    {
        cout << "socket Success" << endl;
    }


    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    // 发送数据
#define NUM 1024
    char inbuffer[NUM];
    string line;
    while (true)
    {
        cout << "Please Enter: ";
        getline(cin, line);     // getline不会读取回车，挺好

        int n = sendto(sock, line.c_str(), line.size(), 0, (struct sockaddr*)&server, sizeof(server));
        if (n < 0) 
        {
            cerr << "sendto Error " << WSAGetLastError() << endl;
            break;
        }
        cout << "sendto Success!!" << n << endl;


        inbuffer[0] = 0; // C语言风格的清空
        struct sockaddr_in peer;
        int len = sizeof(peer);
        
        n = recvfrom(sock, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&peer, &len);
        if(n >= 0) inbuffer[n] = 0;
        cout << inbuffer << endl;
    }

    closesocket(sock);
    WSACleanup();
	return 0;
}